package com.example.customview.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PointF;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;

import androidx.annotation.Nullable;

import java.util.Random;

public class MoveView extends View {
    private Paint paint;
    Context context;
    //圆的初始位置坐标
    private int x=200;
    private int y=200;
    private int radius=100;

    //定义颜色数组
    private int colorArray[] = {Color.BLACK,Color.GRAY,Color.GREEN,Color.YELLOW, Color.RED};

    public MoveView(Context context) {
        super(context);
        this.context=context;
    }

    public MoveView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context=context;
    }

    public MoveView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.context=context;
    }

    /**
     * onDraw方法实现绘制内容
     * @param canvas
     */

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        //用canvas将背景设置成白色
        canvas.drawColor(Color.WHITE);

        //设置画笔
        paint=new Paint();
        setPaintRandomColor();
        //消除锯齿
        paint.setAntiAlias(true);

        canvas.drawCircle(x,y,radius,paint);

    }

    //为画笔设置随机颜色
    private void setPaintRandomColor(){
        Random rand = new Random();
        int randomIndex = rand.nextInt(colorArray.length);
        paint.setColor(colorArray[randomIndex]);
    }

    //实现onTouchEvent方法


    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()){
            case MotionEvent.ACTION_DOWN:
                x=(int)event.getX();
                y= (int) event.getY();
                System.out.println("按下时："+ "x坐标"+event.getRawX()+" "+"y坐标："+event.getRawY());
                break;
            case MotionEvent.ACTION_MOVE:

                x=(int)event.getX();
                y= (int) event.getY();

                System.out.println("移动时："+ "x坐标"+event.getRawX()+" "+"y坐标："+event.getRawY());


                break;
            case MotionEvent.ACTION_UP:

                x=(int)event.getX();
                y= (int) event.getY();

                System.out.println("抬起时："+ "x坐标"+event.getRawX()+" "+"y坐标："+event.getRawY());

                break;
        }

        //获取屏幕高度
        WindowManager manager=(WindowManager)context.getSystemService(context.WINDOW_SERVICE);
        int width=manager.getDefaultDisplay().getWidth();
        int height=manager.getDefaultDisplay().getHeight();

        if (x>=18 && y>=18 && x<= width-18 && y <= height-18){
            postInvalidate();
        }

        return true;
    }
}
